package chances.webui.taglibs;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.jsp.JspException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import chances.system.operator.entity.EnumData;
import chances.system.operator.repo.EnumDataRepository;

public class EnumTag extends WebUITag {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3358552350364711360L;
    private static final Logger logger = LoggerFactory.getLogger(EnumTag.class);

	private String code;
    private String var;
    private boolean appendJs = false;
    
    Map<String, String> result = new LinkedHashMap<String,String>();
    
	@SuppressWarnings("unchecked")
	@Override
	public int doEndTag() throws JspException {
		WebApplicationContext appContext = WebApplicationContextUtils
				.getWebApplicationContext(pageContext.getServletContext());
		EnumDataRepository repos = appContext.getBean(EnumDataRepository.class);
		EnumData enumData = repos.getByCode(code);
		if(enumData != null){
		    try {
        		if (enumData.getType() == EnumData.TYPE_TEXT) {
        			List<EnumData> enums = repos.findByParentId(enumData.getId());
        			 result = enums.stream()
        					.collect(Collectors.toMap(EnumData::getValue, EnumData::getName));
        
        		}else if(enumData.getType()==EnumData.TYPE_HQL){
        			EntityManagerFactory entityManagerFactory = appContext.getBean(EntityManagerFactory.class);
        			EntityManager entityManager = entityManagerFactory.createEntityManager();
        			Query query = entityManager.createQuery(enumData.getValue());
        			List<Object[]> resultList = query.getResultList();
        			result = new LinkedHashMap<String,String>();
        			for (Object[] objects : resultList) {
        				result.put(objects[0].toString(), objects[1].toString());
        			}
        		}
		    } catch (Exception e) {
		        logger.error("Enum["+code+"] error !", e);
            }
		}
		if(result!=null){
			pageContext.setAttribute(this.var, this.result);
		}
		return super.doEndTag();
	}

    @Override
    protected void initContext(Map<String, Object> context) {
        if(result!=null && appendJs){
            context.put("lookups",this.getJson(result));
            context.put("var",this.var);
        }
    }
	
	public String getCode() {
		return code;
	}

	public String getVar() {
		return var;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public boolean isAppendJs() {
        return appendJs;
    }

    public void setAppendJs(boolean appendJs) {
        this.appendJs = appendJs;
    }
}
